/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.tables
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.tables.GetTableDataEvent;
	import com.jonniespratley.flexdatabasemanager.factories.FlexDatabaseManagerFactory;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;


	public class GetTableDataCommand extends SequenceCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		override public function execute( event:CairngormEvent ) : void
		{
			
			var evt:GetTableDataEvent = event as GetTableDataEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				
				if ( model.selectedDatabase == null && model.selectedTable == null )
				{
					//stop the execution and alert the user to select a database and table
					Alert.show( 'You must select a database and or table before requesting data', 'Alert' );
					return; 
					
				} else {
					model.interactingWithServer = true;
					//get the data
					delegate.getTableData( model.currentUser, model.selectedDatabase, model.selectedTable );
				}
		}
		
		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			model.tableDataCollection = FlexDatabaseManagerFactory.parseJSONResult( data.result );
			model.tableDataPagedCollection = FlexDatabaseManagerFactory.parseJSONToPagedCollection( data.result );
			if ( data.result is String )
			{
				//get the raw JSON data and cast to String
				var rawData:String = String( data.result );
				
				//decode the data to ActionScript 
				var tempArray:Array = ( JSON.decode( rawData ) as Array );
					
				//var tempAC:ArrayCollection = new ArrayCollection( tempArray );
				model.tableDataArray = tempArray;
				model.tableDataCollection =  new ArrayCollection( tempArray );
			}
			
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}
	}
}
